<template>
  <div class="plan-manage">
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="计划编号">
        <el-input v-model="searchForm.planId" placeholder="请输入计划编号" clearable />
      </el-form-item>
      <el-form-item label="部门名称">
        <el-select v-model="searchForm.departmentName" placeholder="请选择部门" clearable>
          <el-option 
            v-for="dept in departments"
            :key="dept"
            :label="dept" 
            :value="dept"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input v-model="searchForm.productName" placeholder="请输入产品名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item v-if="showAddButton">
        <el-button type="success" @click="showAddDialog = true">新增计划</el-button>
      </el-form-item>
    </el-form>

    <!-- 计划列表 -->
    <el-table :data="planList" border>
      <el-table-column prop="planId" label="计划编号" width="120" />
      <el-table-column prop="departmentName" label="部门" width="150" />
      <el-table-column prop="productName" label="产品名称" width="180" />
      <el-table-column prop="plannedQuantity" label="计划产量" width="120" />
      <el-table-column prop="actualQuantity" label="实际产量" width="120">
        <template #default="{ row }">
          <span :class="{ 'text-red': row.actualQuantity < row.plannedQuantity }">
            {{ row.actualQuantity || 0 }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="auditStatus" label="审核状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusType[row.auditStatus]">
            {{ statusMap[row.auditStatus] || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="{ row }">
          <el-button 
            v-if="showEditActual" 
            size="small" 
            @click="handleEditActual(row)"
          >
            录入数量
          </el-button>
          <el-button
            v-if="showEditButton"
            size="small"
            type="primary"
            @click="handleEditPlan(row)"
          >
            修改
          </el-button>
          <el-button
            v-if="showDeleteButton"
            size="small"
            type="danger"
            @click="handleDeletePlan(row.planId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="pagination.total"
      :page-size="pagination.size"
      :current-page="pagination.current"
      @current-change="handlePageChange"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog 
      :title="editPlanId ? '修改生产计划' : '新增生产计划'" 
      v-model="showAddDialog"
    >
      <el-form :model="addForm" label-width="120px" :rules="formRules">
        <el-form-item label="部门名称" prop="departmentName">
          <el-select v-model="addForm.departmentName" placeholder="请选择部门">
            <el-option 
              v-for="dept in departments"
              :key="dept"
              :label="dept" 
              :value="dept"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="addForm.productName" />
        </el-form-item>
        <el-form-item label="计划产量" prop="plannedQuantity">
          <el-input-number 
            v-model="addForm.plannedQuantity" 
            :min="1" 
            :step="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false; editPlanId = null">取消</el-button>
        <el-button type="primary" @click="handleSubmitPlan">确定</el-button>
      </template>
    </el-dialog>

    <!-- 录入实际产量对话框 -->
    <el-dialog title="录入实际产量" v-model="showActualDialog">
      <el-form :model="actualForm" label-width="120px">
        <el-form-item label="实际产量">
          <el-input-number
            v-model="actualForm.actualQuantity"
            :min="0"
            :step="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showActualDialog = false">取消</el-button>
        <el-button type="primary" @click="submitActualQuantity">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 状态映射
const statusMap = {
  0: '待审核',
  1: '审核通过',
  2: '审核驳回'
}

const statusType = {
  0: 'warning',
  1: 'success',
  2: 'danger'
}

// 部门列表
const departments = [
  '表面处理车间',
  '锻压车间', 
  '组装车间',
  '质检车间',
  '机加车间'
]

// 权限控制
const userTitle = ref(localStorage.getItem('userTitle') || '普通操作人员')
const showAddButton = computed(() => ['部门经理', '系统管理员'].includes(userTitle.value))
const showEditButton = computed(() => ['部门经理', '系统管理员'].includes(userTitle.value))
const showDeleteButton = computed(() => ['部门经理', '系统管理员'].includes(userTitle.value))
const showEditActual = computed(() => ['普通操作人员', '系统管理员'].includes(userTitle.value))

// 查询表单
const searchForm = reactive({
  planId: '',
  departmentName: '',
  productName: ''
})

// 分页配置
const pagination = reactive({
  total: 0,
  size: 10,
  current: 1
})

// 表格数据
const planList = ref([])

// 对话框控制
const showAddDialog = ref(false)
const showActualDialog = ref(false)
const editPlanId = ref<number | null>(null)

// 表单数据
const addForm = reactive({
  departmentName: '',
  productName: '',
  plannedQuantity: 1000
})

const actualForm = reactive({
  planId: null,
  actualQuantity: 0
})

// 表单验证规则
const formRules = reactive({
  departmentName: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  plannedQuantity: [
    { required: true, message: '请输入计划产量', trigger: 'blur' }
  ]
})

// 获取生产计划数据
const fetchPlans = async (pageNum = 1) => {
  try {
    const params = {
      ...searchForm,
      planId: searchForm.planId || undefined
    }
    
    const res = await axios.post(
      `${import.meta.env.VITE_API_URL}productionPlan/page?pageNum=${pageNum}&pageSize=${pagination.size}`,
      params
    )
    
    planList.value = res.data.records
    pagination.total = res.data.total
    pagination.current = res.data.current
  } catch (e) {
    ElMessage.error('获取数据失败')
  }
}

// 提交生产计划
const handleSubmitPlan = async () => {
  try {
    const url = editPlanId.value 
      ? `${import.meta.env.VITE_API_URL}productionPlan/update`
      : `${import.meta.env.VITE_API_URL}productionPlan/add`

    await axios.post(url, {
      ...addForm,
      planId: editPlanId.value
    })

    ElMessage.success(editPlanId.value ? '修改成功' : '新增成功')
    showAddDialog.value = false
    fetchPlans(pagination.current)
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

// 删除计划
const handleDeletePlan = async (id: number) => {
  try {
    await axios.delete(`${import.meta.env.VITE_API_URL}productionPlan/delete/${id}`)
    ElMessage.success('删除成功')
    fetchPlans(pagination.current)
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

// 录入实际产量
const submitActualQuantity = async () => {
  try {
    await axios.post(`${import.meta.env.VITE_API_URL}productionPlan/update`, {
      planId: actualForm.planId,
      actualQuantity: actualForm.actualQuantity
    })
    ElMessage.success('录入成功')
    showActualDialog.value = false
    fetchPlans(pagination.current)
  } catch (e) {
    ElMessage.error('录入失败')
  }
}

// 打开录入对话框
const handleEditActual = (row: any) => {
  actualForm.planId = row.planId
  actualForm.actualQuantity = row.actualQuantity || 0
  showActualDialog.value = true
}

// 打开编辑对话框并填充数据
const handleEditPlan = (row: any) => {
  editPlanId.value = row.planId
  addForm.departmentName = row.departmentName
  addForm.productName = row.productName
  addForm.plannedQuantity = row.plannedQuantity
  showAddDialog.value = true
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.current = page
  fetchPlans(page)
}

// 初始化数据
onMounted(() => {
  fetchPlans(1)
})
</script>

<style scoped>
.plan-manage {
  padding: 20px;
}

.text-red {
  color: #f56c6c;
}
</style>